#include "stdafx.h"
#include "ImageRenderer.h"
#include "CXComp.h"
#include "Claxa.h"
//#include <mswin/file_dir.h>

void ImageRenderer::Perform()
{
	RendererAPtr deleter(this); //deletes itself if something goes wrong

	PreparePaintingKeys();

	m_Writer = theApp.m_RenderSettings.open_writer(m_Comp.GetDim(), m_Comp.GetExportFramerate(),
		m_Comp.GetFootage().filepath(), String(), AfxGetMainWnd()->m_hWnd);
	if (!m_Writer.get())
		return;

	m_Progress.Create(AfxGetMainWnd());
	m_Progress.Reset(m_PaintingKeys.size());
	//m_Progress.SetWindowText("Exporting masks...");

	mswin::thread::create(true);
	SetThreadPriority(handle(), THREAD_PRIORITY_BELOW_NORMAL);
	deleter.release(); //the object will be deleted in run
}

void ImageRenderer::run()
{
	mswin::thread::set_debug_name("ImageRenderer");
	AsyncDeleteRenderer deleter(this); //deletes itself on finish

	for (;;) {
		Size n = m_Progress.Current();
		if (n >= m_PaintingKeys.size())
			break;
		CachedImageSPtr pIm = GetPainting(m_PaintingKeys[n], 
			(n+1) < m_PaintingKeys.size() ? icache::forward : icache::no_nearby, false);
		m_Writer->add(pIm->im);
		if (!m_Progress.Increment()) {
			AfxMessageBox("Rendering interrupted by user.", MB_ICONEXCLAMATION);
			break;
		}
	}
}

void ImageRenderer::PreparePaintingKeys()
{
	Span w = m_Comp.GetWorkArea();
	m_PaintingKeys.reserve(w.Size());

	CXView & View = theApp.GetFrame().m_View;

	for (int n = w.first; n < w.last; ++n) {
		m_PaintingKeys.push_back(View.GetPaintingKey(n));
	}
}
